package com.handler

import com.amazonaws.services.s3.model.*
import com.amazonaws.services.s3.transfer.MyTransferManager
import org.slf4j.LoggerFactory

class BucketHandler(transferManager: MyTransferManager?) : BaseHandler<String>(transferManager) {
    override fun execute(value: String) {
        if (s3Client?.doesBucketExistV2(value) == true) { // 判断桶是否存在
            System.out.format("Bucket %s already exists.\n", value)
        } else {
            try {
                s3Client?.createBucket(value)
                // 启动版本控制
                s3Client?.setBucketVersioningConfiguration(
                    SetBucketVersioningConfigurationRequest(
                        value,
                        BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED)
                    )
                )
                // 设置安全策略
                val corsRule = CORSRule()
                corsRule.setAllowedOrigins("*")
                corsRule.setAllowedMethods(CORSRule.AllowedMethods.GET)
                corsRule.maxAgeSeconds = 3000
                corsRule.setAllowedHeaders("*")
                s3Client?.setBucketCrossOriginConfiguration(
                    value,
                    BucketCrossOriginConfiguration().withRules(corsRule)
                )

                System.out.format("Bucket %s created successfully.\n", value)
            } catch (e: AmazonS3Exception) {
                LoggerFactory.getLogger(javaClass).error(null, e)
            }
        }

        // 关闭client
        transferManager?.shutdownNow()
    }
}
